package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.CouponOperationPageQueryReqDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;

    @Resource
    private CouponMapper couponMapper;

    /**
     * 分页查询优惠劵领取记录
     *
     * @return
     */
    @Override
    public PageResult<Coupon> addpage(CouponOperationPageQueryReqDTO couponOperationPageQueryReqDTO) {
        Page page = Page.of(
                Math.toIntExact(couponOperationPageQueryReqDTO.getPageNo()),
                Math.toIntExact(couponOperationPageQueryReqDTO.getPageSize())
        );
        LambdaQueryWrapper<Coupon> queryWrapper = Wrappers.<Coupon>lambdaQuery()
                .eq(Coupon::getActivityId, couponOperationPageQueryReqDTO.getActivityId())
                .orderByDesc(Coupon::getCreateTime);

        // 执行分页查询
        Page<Coupon> mybatisPage = new Page<>(page.getPages(), page.getSize());

        // 调用mapper进行分页查询
        couponMapper.selectPage(mybatisPage, queryWrapper);

        // 封装返回结果
        PageResult<Coupon> tPageResult = PageResult.of(
                mybatisPage.getRecords(),
                Math.toIntExact(mybatisPage.getSize()),
                mybatisPage.getPages(),
                mybatisPage.getTotal());

        return tPageResult;
    }


}
